package com.yanhui.api.file;

import com.yanhui.modal.file.HtmlToPdfInterceptor;
import com.yanhui.tojpg.CompositeImage;
import com.yanhui.tojpg.Pdf2Jpg;
import com.yanhui.utils.http._httpUtils;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;



/**
 * @Description ${END}
 * @Author yanhui
 * @Date 2018-12-23 14:50
 */
public class HtmlApi {

//    public static void main(String[] args) {
//        String htmlPath = "http://47.98.237.162/index";
//        String pdfPath = "C://yhfile//pdf//testpdf2.pdf";
//        getHtmlToPdf(htmlPath, pdfPath);
//
////        String outName = "test.jpg";
////        String sourceFile = pdfPath;
////        String destFile ="C://yhfile//pic//";
//
//        String outName = "C://yhfile//pic//test.jpg";
//        String sourceFile = "C://yhfile//pdf//testpdf2.pdf";
//        String destFile = "";
//        //主页图片在pic文件下，分页图片在pdf下，testpdf2_1.jpg
//        getPdfToPic(sourceFile, destFile, outName);
//
//    }

    /**
     * html转pdf
     * 文件下载：HTML转PDF工具（wkhtmltopdf）介绍，支持widows和linux
     * wkhtmltopdf下载地址：链接：http://pan.baidu.com/s/1jIkk9Wa 密码：ljn6
     */
    public static boolean getHtmlToPdf(String htmlPath, String pdfPath){
        File file = new File(pdfPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }

        //c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf"
        StringBuilder cmd = new StringBuilder();
        cmd.append("C://yhfile//exe//wkhtmltopdf//bin//wkhtmltopdf.exe");
        cmd.append(" ");
        cmd.append(htmlPath);
        cmd.append(" ");
        cmd.append(pdfPath);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(
                    proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            System.out.println("HTML2PDF成功，参数---html路径：{},pdf保存路径 ：{}"+new Object[] {htmlPath, pdfPath});
        } catch (Exception e) {
            System.out.println(("HTML2PDF失败，srcPath地址：{},错误信息：{}"));
            result = false;
        }
        return  result;
    }

    /**
     * pdf转图片
     */
    public static void getPdfToPic(String sourceFile, String destFile, String outName){
        try {
            int page = Pdf2Jpg.tranfer(sourceFile, destFile);
            String page_ = page + "";
            if(page_ .equals("2")){
                CompositeImage.CompositeImage2(outName);
            }else if(page_ .equals("3")){
                CompositeImage.CompositeImage3(outName);
            }else if(page_ .equals("4")){
                CompositeImage.CompositeImage4(outName);
            }else if(page_ .equals("5")){
                CompositeImage.CompositeImage5(outName);
            }else{
                System.out.println(page);
            }
        } catch (PDFException e) {
            e.printStackTrace();
        } catch (PDFSecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * text转markdown
     * 1、二级标题
     */
    public static String getTextToMarkdown(String text){
        String reg = "\\d+、";
        text = text.replaceAll(reg, "## ");
        return text;
    }

    public static void main(String[] args) {
        String text = "1、项目80端口启动\n" +
                "\n" +
                "2、下载ngrok\n" +
                "cmd打开ngrok.exe http 80\n" +
                "\n" +
                "3、项目配置appid、serect、token\n" +
                "\n" +
                "4、访问URL http://10119b9b.ngrok.io/yh_goods/wxCore/wxCore1.html\n" +
                "\n" +
                "responbody访问字符串给微信后台\n" +
                "\n" +
                "5、访问微信扫码\n" +
                "\n" +
                "6、main方法运行，配置公众号菜单";
        String a = getTextToMarkdown(text);
        System.out.println(a);
    }

    /**
     * 一键采集网页 生成标题 内容 html 图片
     * @param title_
     * @param content_
     * @param url_
     * @throws Exception
     */
    public static void getHtmlArticle(String title_, String content_, String url_) throws Exception {
        String url = "https://www.x6tt.cn/post/157.html";
        Document docunment = Jsoup.parse(new URL(url),3000);
        Elements elements = docunment.getElementsByTag("h1");
        String title = elements.get(0).html();
        Elements elements2 = docunment.getElementsByClass("entry-content");
        String content = elements2.get(0).html();
        Elements imgs = elements2.get(0).getElementsByTag("img");
        List<String> imgList = new ArrayList<String>();
        for (Element element : imgs) {
            String imgSrc = element.attr("abs:src");
            String imgSrc2 = element.attr("abs:data-original");
            if(!imgSrc2.equals("")){
                String imgSrc2_ = getSinaImg(imgSrc2);
                String imgSrc_ = getSinaImg(imgSrc);
                imgList.add(imgSrc_);
                imgList.add(imgSrc2_);
                content = content.replaceAll(imgSrc, imgSrc_);
                content = content.replaceAll(imgSrc2, imgSrc2_);
            }
        }
        System.out.println(content);
    }

    /**
     * 通过在线img获取新浪图床
     * @param url
     * @return
     */
    public static String getSinaImg(String url){
        String html = _httpUtils.get("https://api.yum6.cn/sinaimg.php?img="+url);
        if(html.indexOf("\"pid\":\"")>0){
            html = html.substring(html.indexOf("\"pid\":\"")+7);
            html = html.substring(0,html.indexOf("\""));
            html = "https://ww2.sinaimg.cn/large/"+html+".jpg";
            return html;
        }
        return url;
    }

    public static String getImageUrl(String pid, int sizeidx, boolean https) {
        String[] sizeArr = new String[]{"large", "mw1024", "mw690", "bmiddle", "small", "thumb180", "thumbnail", "square"};
        pid = pid.trim();
        String size = sizeArr[sizeidx];
        Pattern p = Pattern.compile("^[a-zA-Z0-9]{32}$");
        Matcher m = p.matcher(pid);
        if (m.matches()) {
            System.out.println("匹配了");
            CRC32 crc32 = new CRC32();
            crc32.update(pid.getBytes());
            return (https ? "https" : "http") + "://" + (https ? "ws" : "ww")
                    + ((crc32.getValue() & 3) + 1) + ".sinaimg.cn/" + size
                    + "/" + pid + "." + (pid.charAt(21) == 'g' ? "gif" : "jpg");
        }
        String url = pid;
        Pattern p1 = Pattern.compile("^(https?://[a-z]{2}d.sinaimg.cn/)(large|bmiddle|mw1024|mw690|small|square|thumb180|thumbnail)(/[a-z0-9]{32}.(jpg|gif))$");
        Matcher m1 = p1.matcher(url);
        if (m1.find()) {
            return m.group(1) + size + m.group(3);
        }
        return null;
    }

}
